package com.example.sprintboot.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.sprintboot.entity.Cart;
import com.example.sprintboot.entity.CartItem;
import com.example.sprintboot.entity.Product;
import com.example.sprintboot.mapper.CartItemMapper;
import com.example.sprintboot.mapper.CartMapper;
import com.example.sprintboot.mapper.ProductMapper;
import com.example.sprintboot.service.CartService;
import com.example.sprintboot.vo.CartItemVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class CartServiceImpl implements CartService {
    @Autowired
    private CartItemMapper cartItemMapper;
    @Autowired
    private CartMapper cartMapper;
    @Autowired
    private ProductMapper productMapper;

    @Override
    public List<CartItemVO> getCartItems(Integer userId) {
        // 先获取用户的购物车ID
        Cart cart = cartMapper.selectOne(new QueryWrapper<Cart>().eq("user_id", userId));
        if (cart == null) {
            return List.of(); // 用户没有购物车，返回空列表
        }
        
        List<CartItem> items = cartItemMapper.selectList(new QueryWrapper<CartItem>().eq("cart_id", cart.getCartId()));
        return items.stream().map(item -> {
            Product product = productMapper.selectById(item.getProductId());
            CartItemVO vo = new CartItemVO();
            vo.setItemId(item.getItemId());
            vo.setProductId(item.getProductId());
            vo.setProductName(product.getName());
            vo.setProductImage(product.getMainImage());
            vo.setPrice(product.getPrice());
            vo.setQuantity(item.getQuantity());
            vo.setSubtotal(product.getPrice().multiply(BigDecimal.valueOf(item.getQuantity())));
            vo.setSelected(item.getSelected() != null && item.getSelected() == 1);
            return vo;
        }).collect(Collectors.toList());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addCartItem(Integer userId, Integer productId, Integer quantity) {
        // 验证商品是否存在且上架
        Product product = productMapper.selectById(productId);
        if (product == null) {
            throw new RuntimeException("商品不存在");
        }
        if (product.getStatus().getValue() != 1) {
            throw new RuntimeException("商品已下架");
        }
        
        // 验证库存
        if (quantity > product.getStock()) {
            throw new RuntimeException("库存不足，当前库存: " + product.getStock() + "，请求数量: " + quantity);
        }
        
        // 获取或创建用户的购物车
        Cart cart = cartMapper.selectOne(new QueryWrapper<Cart>().eq("user_id", userId));
        if (cart == null) {
            cart = new Cart();
            cart.setUserId(userId);
            cart.setCreateTime(LocalDateTime.now());
            cartMapper.insert(cart);
        }
        
        // 检查购物车中是否已存在该商品
        CartItem exist = cartItemMapper.selectOne(
            new QueryWrapper<CartItem>()
                .eq("cart_id", cart.getCartId())
                .eq("product_id", productId)
        );
        
        if (exist != null) {
            // 如果已存在，更新数量
            int newQty = exist.getQuantity() + quantity;
            if (newQty > product.getStock()) {
                throw new RuntimeException("库存不足，当前库存: " + product.getStock() + "，总需求数量: " + newQty);
            }
            exist.setQuantity(newQty);
            exist.setCreateTime(LocalDateTime.now());
            cartItemMapper.updateById(exist);
        } else {
            // 如果不存在，创建新的购物车项
            CartItem item = new CartItem();
            item.setCartId(cart.getCartId());
            item.setProductId(productId);
            item.setQuantity(quantity);
            item.setSelected(1);
            item.setCreateTime(LocalDateTime.now());
            cartItemMapper.insert(item);
        }
    }

    @Override
    public void updateCartItem(Integer userId, Integer itemId, Integer quantity, Boolean selected) {
        CartItem item = cartItemMapper.selectById(itemId);
        if (item != null) {
            // 验证购物车项是否属于该用户
            Cart cart = cartMapper.selectById(item.getCartId());
            if (cart != null && cart.getUserId().equals(userId)) {
                Product product = productMapper.selectById(item.getProductId());
                if (product == null || product.getStatus().getValue() != 1) {
                    throw new RuntimeException("商品不存在或已下架");
                }
                if (quantity > product.getStock()) {
                    throw new RuntimeException("库存不足");
                }
                item.setQuantity(quantity);
                item.setSelected(selected ? 1 : 0);
                cartItemMapper.updateById(item);
            }
        }
    }

    @Override
    public void deleteCartItem(Integer userId, Integer itemId) {
        CartItem item = cartItemMapper.selectById(itemId);
        if (item != null) {
            // 验证购物车项是否属于该用户
            Cart cart = cartMapper.selectById(item.getCartId());
            if (cart != null && cart.getUserId().equals(userId)) {
                cartItemMapper.deleteById(itemId);
            }
        }
    }

    @Override
    public void batchDeleteCartItems(Integer userId, List<Integer> itemIds) {
        for (Integer itemId : itemIds) {
            deleteCartItem(userId, itemId);
        }
    }

    @Override
    public void clearCart(Integer userId) {
        Cart cart = cartMapper.selectOne(new QueryWrapper<Cart>().eq("user_id", userId));
        if (cart != null) {
            cartItemMapper.delete(new QueryWrapper<CartItem>().eq("cart_id", cart.getCartId()));
        }
    }

    @Override
    public void mergeCart(Integer userId, List<CartItemVO> items) {
        for (CartItemVO vo : items) {
            addCartItem(userId, vo.getProductId(), vo.getQuantity());
        }
    }

    @Override
    public void batchCheckout(Integer userId, List<Integer> itemIds) {
        // 这里只做接口，实际结算逻辑在订单模块
    }
} 